//
//  GTMultithreadDemo.m
//  semple-code-oc
//
//  Created by zhaoguoteng on 2021/12/8.
//

#import "GTMultithreadDemo.h"

@implementation GTMultithreadDemo

+ (void)test {
    
//    [self test01];
    
//    [self test02];
    
    [self test03];
}

+ (void)test01 {
    
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(1);
    
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
//    dispatch_queue_t queue = dispatch_queue_create("queue", DISPATCH_QUEUE_SERIAL);
    dispatch_apply(20, queue, ^(size_t iteration) {
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        sleep(0.5);
        NSLog(@"########## iteration = %zu %@", iteration, NSThread.currentThread);
        dispatch_semaphore_signal(semaphore);
    });
    
    NSLog(@"########## 结束");
}

+ (void)test02 {
    
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    for (int i = 0; i < 20; i++) {
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            NSLog(@"########## i = %d %@", i, NSThread.currentThread);
            dispatch_semaphore_signal(semaphore);
        });
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    }
}

+ (void)test03 {
    dispatch_source_t source = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(0, 0));
    dispatch_source_set_timer(source, DISPATCH_TIME_NOW, 2.0*NSEC_PER_SEC, 0.1 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(source, ^{
        NSLog(@"############# gcd timer");
    });
    dispatch_resume(source);
}

@end
